<template>
  <h2>侦听器</h2>
  <p>count: {{ count }}</p>
  <button @click="add">btn</button>

  <p>{{ obj }}</p>
  <button @click="change">btn2</button>
</template>

<script>
// 侦听器要从vue解构watch函数
import { ref, watch } from "vue";
export default {
  setup() {
    const count = ref(3);
    const add = () => {
      count.value++;
    };

    const obj = ref({
      name: "zhangsan",
      age: 20,
    });

    const change = () => {
      obj.value.age++;
    };

    // 传入至少两个参数,第一个是要监听的变量名，没有引号，第二个是回调函数
    // 第二个回调函数有两个参数(选填)

    // 还有第三个参数是选项对象, deep, immediate
    watch(count, (val, oldVal) => {
      console.log(`count从${oldVal}改变了${val}`);
    });
    watch(
      obj,
      (val, oldVal) => {
        console.log(`obj改变了`);
      },
      {
        deep: true, // 深度监听
        immediate: true, // 进入页面先做一次
      }
    );

    return { count, add, obj, change };
  },
};
</script>
